/**   
 * �ļ���UserAction.java</br>
 * ������ </br>
 * ������Ա�����Ʋ� </br>
 * ����ʱ�䣺 2016-4-17
 */ 

package com.user.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.base.BaseAction.BaseAction;
import com.base.util.OperateImage;
import com.base.util.Page;
import com.base.util.DateUtil;
import com.opensymphony.xwork2.ModelDriven;
import com.post.bean.PostVO;
import com.post.service.PostService;
import com.user.bean.BBSUser;
import com.user.bean.UserCollect;
import com.user.bean.UserFocus;
import com.user.service.UserService;

/**
 * 类名: UserAction</br> 
 * 包名：com.user.action </br> 
 * 描述: 用户Action</br>
 * 发布版本号：</br>
 * 开发人员： 汪浩博</br>
 * 创建时间： 2016-5-4
 */
public class UserAction extends BaseAction implements ModelDriven<BBSUser>{
	
	private static final long serialVersionUID = 6172140041139939607L;
	private static final String REGIST = "regist";
	private String callbackurl;
	private BBSUser bbsuser = new BBSUser();//用户
	private UserService userService;
	private PostService postService;
	
	private String authcode;			//验证码
	private String oldpassword;
	private String newpassword;
	private String repeatpassword;
	private String focusUserid;			//被关注的用户id
	
	private Integer pagenum = 1;
	private String formData;
	private OperateImage image = new OperateImage();//(省略get set)
	private File pic; // 接收这个上传的文件
	private String picFileName; // Struts2提供的格式，在文件名后+FileName就是上传文件的名字
	
	private String x;
	private String y;
	private String w;
	private String h;
	/**
	 * 方法名: getPageUser</br>
	 * 详述: 分页查询用户</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-3</br>
	 * @return
	 */
	public String getPageUser(){
		Page querypage = userService.Querypage(bbsuser, pagenum, pagesize);
		this.getRequest().setAttribute("querypage", querypage);
		return "list";
	}
	/**
	 * 方法名: regist</br>
	 * 详述: 注册</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-5</br>
	 * @return
	 */
	public String regist(){
		HttpSession session = ServletActionContext.getRequest().getSession();
        String checkCode2 = (String)session.getAttribute("checkCode");
		if(!authcode.equals(checkCode2)){
			//验证码不对
			this.getRequest().setAttribute("authcode_flag", true);
			return REGIST;
		}
		boolean exist_flag = userService.checkUser(bbsuser);
		if(exist_flag){
			//检查是否存在此用户
			this.getRequest().setAttribute("exist_flag", exist_flag);
		}else{
			Date date = new Date();//获取当前系统时间
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");//设置格式化格式
			bbsuser.setNickName("用户"+sdf2.format(date));//设置默认的昵称
			bbsuser.setRegistTime(DateUtil.getStringTime());
			bbsuser.setStatus("0");//正常0（默认）
			bbsuser.setSex("1");//默认性别为  男
			bbsuser.setHeadImg("../images/avatar.php");//默认头像
			bbsuser.setFansNum(0);
			bbsuser.setConcernNum(0);
			userService.addUser(bbsuser);
			this.getRequest().setAttribute("exist_flag", exist_flag);
		}
		return REGIST;
	}
	/**
	 * 方法名: login</br>
	 * 详述: 登录</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-5</br>
	 * @return
	 */
	public String login(){
		HttpSession session = ServletActionContext.getRequest().getSession();
        String checkCode2 = (String)session.getAttribute("checkCode");
		if(!authcode.equals(checkCode2)){
			//验证码不对
			this.getRequest().setAttribute("authcode_flag", true);
			return INPUT;
		}
		BBSUser loginUser = userService.Login(bbsuser);
		if(loginUser != null){
			//检查是否存在此用户
			this.getRequest().setAttribute("exist_flag", "true");
			this.getSession().put("user", loginUser);
			return LOGIN;
		}else{
			this.getRequest().setAttribute("exist_flag", "false");
			return INPUT;
		}
	}
	/**
	 * 方法名: logoff</br>
	 * 详述: 退出登录</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-5</br>
	 * @return
	 */
	public String logoff(){
		this.getSession().remove("user");
		return "logoff";
	}
	/**
	 * 方法名: UpdateUserInfo</br>
	 * 详述: 更新单个用户</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-6</br>
	 * @return
	 */
	public String updateUserInfo(){
		BBSUser loginUser = this.getLoginUser();
		loginUser.setNickName(bbsuser.getNickName());
		loginUser.setSex(bbsuser.getSex());
		loginUser.setPhone(bbsuser.getPhone());
		loginUser.setProvinces(bbsuser.getProvinces());
		loginUser.setLocal(bbsuser.getLocal());
		boolean update_flag = userService.updateUser(loginUser);
		this.getRequest().setAttribute("update_flag", update_flag);
		this.getSession().put("user", bbsuser);
		return "updateUser";
	}
	/**
	 * 方法名: resetPwd</br>
	 * 详述: 修改密码</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-6</br>
	 * @return
	 */
	public String resetPwd(){
		String rePwd_flag = "0";
		BBSUser loginUser = this.getLoginUser();
		if(loginUser.getPassword().equals(oldpassword)){
			rePwd_flag = "0";//旧密码正确
		}else{
			rePwd_flag = "1";//旧密码不正确
			this.getRequest().setAttribute("rePwd_flag", rePwd_flag);
			return "resetPwd";
		}
		loginUser.setPassword(newpassword);
		if(!newpassword.equals(repeatpassword)){
			rePwd_flag = "2";//密码不一致
			this.getRequest().setAttribute("rePwd_flag", rePwd_flag);
			return "resetPwd";
		}else if(userService.updateUser(loginUser)){
			rePwd_flag = "0";//密码修改成功
			this.getRequest().setAttribute("rePwd_flag", rePwd_flag);
			this.getSession().put("user", loginUser);
		}
		return "resetPwd";
	}
	/**
	 * 方法名: uploadPic</br>
	 * 详述: 上传图片</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-18</br>
	 * @return
	 */
	public String uploadPic() {
		JSONObject json = new JSONObject();
		String[] str = { ".jpg", ".jpeg", ".bmp", ".gif",".png" };
		// 获取用户登录名
		BBSUser loginUser = this.getLoginUser();
		String userName = loginUser.getUserName();
		// 限定文件大小是4MB
		if (pic == null || pic.length() > 4194304) {
			//文件过大
			return "error";
		}
		String stringTime = userName + "_" + DateUtil.getStringTime2();
		for (String s : str) {
			if (picFileName.endsWith(s)) {
				String realPath = ServletActionContext.getServletContext().getRealPath("/uploadpic");// 在tomcat中保存图片的实际路径  ==  "webRoot/uploadpic/"
				File saveFile = new File(new File(realPath), stringTime + s); // 在该实际路径下实例化一个文件
				// 判断父目录是否存在
				if (!saveFile.getParentFile().exists()) {
					saveFile.getParentFile().mkdirs();
				}
				try {
					// 执行文件上传
					// FileUtils 类名 org.apache.commons.io.FileUtils;
					// 是commons-io包中的，commons-fileupload 必须依赖
					// commons-io包实现文件上传，实际上就是将一个文件转换成流文件进行读写
					FileUtils.copyFile(pic, saveFile);
					String imgPath = "../uploadpic/"+stringTime + s;
					loginUser.setHeadImg(imgPath);
					userService.updateUser(loginUser);
					this.getSession().put("user", loginUser);
					json.put("status", 2000);
				} catch (IOException e) {
					json.put("message", "图片上传出错");
				}
			}else{
				json.put("message", "文件类型不对");//文件类型不对
			}
		}
		json.put("info", loginUser);
		this.writeJSON(json.toString());
		return null;
	}
	
	/**
	 * 裁剪头像
	 */
	public String cutPic(){
		JSONObject json = new JSONObject();
		// 获取用户登录名
		BBSUser loginUser = this.getLoginUser();
		String headImg = loginUser.getHeadImg();
		String headImg2 = headImg.substring(headImg.indexOf("uploadpic"));
		String name = ServletActionContext.getServletContext().getRealPath(headImg2);
		String imgType = name.substring(name.lastIndexOf("."));
		image.setX(Integer.parseInt(x));
		image.setY(Integer.parseInt(y));
		image.setWidth(Integer.parseInt(w));
		image.setHeight(Integer.parseInt(h));
		image.setSrcpath(name);
		image.setSubpath(ServletActionContext.getServletContext().getRealPath(headImg2));
		try {
			image.cut(imgType); //执行裁剪操作  执行完后即可生成目标图在对应文件夹内。
			json.put("status", 2000);
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.writeJSON(json.toString());
		return null;
	}
	/**
	 * 方法名: personCollect</br>
	 * 详述: 通过用户id查询相关收藏的帖子</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-21</br>
	 * @return
	 */
	public String personCollect(){
		Long id = this.getLoginUser().getId();
		Page querypage = postService.findCollectPostByUid(id,pagenum,pagesize);
		//将结果集转换成VO
		PostVO postVo = new PostVO();
		List queryResult = querypage.getQueryResult();
		List<PostVO> list = postVo.beanTransVo(queryResult,userService);
		//将原有的结果集替换成VO结果集
		querypage.setQueryResult(list);
		this.getRequest().setAttribute("page", querypage);
		return "personCollect";
	}
	/**
	 * 方法名: collectPost</br>
	 * 详述: 收藏帖子</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-21</br>
	 * @return
	 */
	public String collectPost(){
		JSONObject json = new JSONObject();
		String pid = this.getRequest().getParameter("pid");
		Long uid = this.getLoginUser().getId();
		UserCollect collect = new UserCollect();
		collect.setPid(pid);
		collect.setUserid(uid.toString());
		//检查是否已经收藏
		boolean checkCollectExist = userService.checkCollectExist(collect);
		if(!checkCollectExist){
			//新增收藏记录
			boolean flag_collect = userService.addCollect(collect);
			if(flag_collect){
				json.put("collect", true);
			}
		}
		this.writeJSON(json.toString());
		return null;
	}
	/**
	 * 方法名: cancelCollect</br>
	 * 详述: 取消收藏</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-5-21</br>
	 * @return
	 */
	public String cancelCollect(){
		String pid = this.getRequest().getParameter("pid");
		boolean cancel = userService.cancelCollect(pid);
		if(cancel){
			this.getRequest().setAttribute("cancel", cancel);
		}
		return "cancelCollect";
	}
	/**
	 * 方法名: personFocus</br>
	 * 详述: 通过用户id查询相关关注的用户</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-10</br>
	 * @return
	 */
	public String personFocus(){
		Long id = this.getLoginUser().getId();
		Page querypage = userService.findFocusUserById(id, 1, 1000);
		this.getRequest().setAttribute("page", querypage);
		return "personFocus";
	}
	/**
	 * 方法名: focusUser</br>
	 * 详述: 关注用户</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-10</br>
	 * @return
	 */
	public String focusUser(){
		focusUserid = this.getRequest().getParameter("focusUserid");
		BBSUser loginUser = this.getLoginUser();
		BBSUser focusUser = userService.findUserById(focusUserid);//被关注的用户
		Long uid = loginUser.getId();
		UserFocus focus = new UserFocus();
		focus.setUserid(uid.toString());
		focus.setFocusUserid(focusUserid);
		
		//检查是否已经关注
		boolean checkCollectExist = userService.checkFocusExist(focus);
		if(!checkCollectExist){
			//新增关注记录
			boolean flag_focus = userService.addFocus(focus);
			if(flag_focus){
				//关注成功
				loginUser.setConcernNum(loginUser.getConcernNum() + 1);//登录的用户关注数+1
				focusUser.setFansNum(focusUser.getFansNum() + 1);//被关注的用户 粉丝数 +1
				userService.updateUser(loginUser);
				userService.updateUser(focusUser);
				this.getSession().put("user", loginUser);
			}
		}
		return "focusUser";
	}
	/**
	 * 方法名: cancelFocus</br>
	 * 详述: 取消关注</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-12</br>
	 * @return
	 */
	public String cancelFocus(){
		//当前登录用户id
		BBSUser loginUser = this.getLoginUser();
		Long id = loginUser.getId();
		String bbsUserId = this.getRequest().getParameter("bbsUserId");
		userService.cancelFocus(id,bbsUserId);
		//更新关注数和粉丝数
		BBSUser focusUser = userService.findUserById(bbsUserId);
		loginUser.setConcernNum(loginUser.getConcernNum() - 1);//登录的用户关注数-1
		focusUser.setFansNum(focusUser.getFansNum() - 1);//被关注的用户 粉丝数 -1
		userService.updateUser(loginUser);
		userService.updateUser(focusUser);
		this.getSession().put("user", loginUser);
		
		focusUserid = bbsUserId;
		return "cancelFocus";
	}
	/**
	 * 方法名: getPersonHome</br>
	 * 详述: 获取个人首页</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-10</br>
	 * @return
	 */
	public String getPersonHome(){
		//获取用户id
		String uid = this.getRequest().getParameter("uid");
		BBSUser bbsUser = userService.findUserById(uid);
		//查看当前登录用户是否关注该用户
		BBSUser loginUser = this.getLoginUser();
		if (loginUser != null){
			Long loginUserId = this.getLoginUser().getId();
			UserFocus focus = new UserFocus();
			focus.setFocusUserid(uid);
			focus.setUserid(loginUserId.toString());
			boolean checkFocusExist = userService.checkFocusExist(focus);
			if (checkFocusExist) {
				//当前登录用户已关注 该用户
				this.getRequest().setAttribute("checkFocusExist", true);
			}
		}
		Page focusPage = userService.findFocusUserById(Long.parseLong(uid), 1, 10);//只查询该用户关注的十个用户
		Page fansPage = userService.findFansUserById(Long.parseLong(uid), 1, 10);//只查询该用户的十个粉丝
		this.getRequest().setAttribute("focusList", focusPage.getQueryResult());
		this.getRequest().setAttribute("fansList", fansPage.getQueryResult());
		this.getRequest().setAttribute("bbsUser", bbsUser);
		return "personHome";
	}
	/**
	 * 方法名: banSpeech</br>
	 * 详述: 禁言用户</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-6</br>
	 * @return
	 */
	public String banSpeech(){
		String pid = this.getRequest().getParameter("pid");
		BBSUser user = userService.findUserById(pid);
		user.setStatus("-1");//禁言，修改用户状态为 -1
		userService.updateUser(user);
		return "banspeech";
	}
	/**
	 * 方法名: cancelBanSpeech</br>
	 * 详述: 取消禁言</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-8</br>
	 * @return
	 */
	public String cancelBanSpeech(){
		String pid = this.getRequest().getParameter("pid");
		BBSUser user = userService.findUserById(pid);
		user.setStatus("0");//取消禁言，修改用户状态为 0
		userService.updateUser(user);
		return "cancelbanspeech";
	}
	/**
	 * 方法名: updateModerator</br>
	 * 详述: 设置版主</br>
	 * 开发人员：汪浩博</br>
	 * 创建时间：2016-6-8</br>
	 * status 	1 装备交流 2 活动发布  3 游记攻略  4 优秀个人  5 户外摄影
	 * @return
	 */
	public String updateModerator(){
		String uid = this.getRequest().getParameter("uid");
		String userstatus = this.getRequest().getParameter("userstatus");
		BBSUser user = userService.findUserById(uid);
		user.setStatus(userstatus);
		userService.updateUser(user);
		return "updateModerator";
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getAuthcode() {
		return authcode;
	}

	public void setAuthcode(String authcode) {
		this.authcode = authcode;
	}

	public String getCallbackurl() {
		return callbackurl;
	}
	public void setCallbackurl(String callbackurl) {
		this.callbackurl = callbackurl;
	}
	
	public String getOldpassword() {
		return oldpassword;
	}
	public void setOldpassword(String oldpassword) {
		this.oldpassword = oldpassword;
	}
	public String getNewpassword() {
		return newpassword;
	}
	public void setNewpassword(String newpassword) {
		this.newpassword = newpassword;
	}
	public String getRepeatpassword() {
		return repeatpassword;
	}
	public void setRepeatpassword(String repeatpassword) {
		this.repeatpassword = repeatpassword;
	}
	public OperateImage getImage() {
		return image;
	}
	public void setImage(OperateImage image) {
		this.image = image;
	}
	public File getPic() {
		return pic;
	}
	public void setPic(File pic) {
		this.pic = pic;
	}
	public String getPicFileName() {
		return picFileName;
	}
	public void setPicFileName(String picFileName) {
		this.picFileName = picFileName;
	}
	public String getFormData() {
		return formData;
	}
	public void setFormData(String formData) {
		this.formData = formData;
	}
	public String getX() {
		return x;
	}
	public void setX(String x) {
		this.x = x;
	}
	public String getY() {
		return y;
	}
	public void setY(String y) {
		this.y = y;
	}
	public String getW() {
		return w;
	}
	public void setW(String w) {
		this.w = w;
	}
	public String getH() {
		return h;
	}
	public void setH(String h) {
		this.h = h;
	}
	public Integer getPagenum() {
		return pagenum;
	}
	public void setPagenum(Integer pagenum) {
		this.pagenum = pagenum;
	}
	public PostService getPostService() {
		return postService;
	}
	public void setPostService(PostService postService) {
		this.postService = postService;
	}
	public String getFocusUserid() {
		return focusUserid;
	}
	public void setFocusUserid(String focusUserid) {
		this.focusUserid = focusUserid;
	}
	@Override
	public BBSUser getModel() {
		return this.bbsuser;
	}
}
